import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class StudentJoin {

    public static class StudentMapper extends Mapper<LongWritable, Text, Text, Text> {

        private final Text outKey = new Text();
        private final Text outValue = new Text();

        @Override
        protected void map(LongWritable key, Text value, Context context)
                throws IOException, InterruptedException {
            String[] parts = value.toString().split(",");
            if (parts.length == 2) { // student.txt
                outKey.set(parts[0]);
                outValue.set("student$" + parts[1]);
                context.write(outKey, outValue);
            } else if (parts.length == 3) { // student_score.txt
                outKey.set(parts[0]);
                outValue.set("score$" + parts[1] + "," + parts[2]);
                context.write(outKey, outValue);
            }
        }
    }

    public static class JoinReducer extends Reducer<Text, Text, Text, Text> {

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context)
                throws IOException, InterruptedException {
            List<String> students = new ArrayList<>();
            List<String> scores = new ArrayList<>();

            for (Text value : values) {
                String[] parts = value.toString().split("\\$");
                if (parts[0].equals("student")) {
                    students.add(parts[1]);
                } else if (parts[0].equals("score")) {
                    scores.add(parts[1]);
                }
            }

            for (String student : students) {
                for (String score : scores) {
                    context.write(null, new Text(key + "," + student + "," + score));
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "student join");
        job.setJarByClass(StudentJoin.class);
        job.setMapperClass(StudentMapper.class);
        job.setReducerClass(JoinReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
